<template>
  <div class="choose-org-root">
    <div class="input-container" @click="openDialog">
      <el-tag
          v-for="tag in checkList"
          :key="tag.orgCode"
          closable
          class="diy-tag"
          @close="removeItem(tag)"
          :type="tag.orgType == '1' ? ''  : 'success'">
        {{ tag.orgName }}
      </el-tag>
    </div>

    <el-dialog ref="dialog" title="选择组织" show-close modal :visible.sync="open" width="1100px" append-to-body>
      <div v-if="open" class="app-container">
        <org-list @change="handleSelectionChange"></org-list>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {isArr} from "@/utils/arrayUtil";
import OrgList from "@/views/components/OrgList.vue";
export default {
  components:{
    OrgList
  },
  props: {
    value: {
      type: Array
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      dataList: [],
      checkList: [],
      bufferCheckList: [],
      open: false,
    }
  },
  watch: {
    value: {
      handler(val) {
        if (isArr(val)) {
          this.checkList = val
        }else {
          this.checkList = []
        }
      },
      deep: true,
    },
    checkList: {
      handler(val) {
        if (isArr(val) && JSON.stringify(val) !== JSON.stringify(this.value)) {
          this.$emit('change', val)
        }
      },
      deep: true,
    }
  },
  methods: {
    removeItem(item) {
      this.checkList = this.checkList.filter(cItem => cItem.orgCode !== item.orgCode)
    },
    handleSelectionChange(selection) {
      this.bufferCheckList = selection
    },
    cancel() {
      this.open = false
    },
    submitForm() {
      this.bufferCheckList.forEach(item => {
        if (!this.checkList.some(cItem => cItem.orgCode == item.orgCode)) {
          this.checkList.push(item)
        }
      })
      this.cancel()
    },
    openDialog() {
      this.bufferCheckList = []
      this.open = true
    },
  },
};
</script>

<style lang="scss" scoped>

</style>
